import java.util.Arrays;

public class Demo02 {
    //递归
    public static void mergeSort1(int[] array){
        mergeSortFunc(array,0,array.length-1);
    }
    private static void mergeSortFunc(int[] array,int left,int right){
        if(left>=right){
            return;
        }
        int mid=(left+right)/2;
        mergeSortFunc(array,left,mid);
        mergeSortFunc(array,mid+1,right);
        merge(array,left,right,mid);
    }
    private static void merge(int[] array,int start,int end,int mid){
        int s1=start;
        int s2=mid+1;
        int[] tmp=new int[end-start+1];
        int k=0;
        while (s1<=mid&&s2<=end){
            if(array[s1]<=array[s2]){
                tmp[k++]=array[s1++];
            }else{
                tmp[k++]=array[s2++];
            }
        }
        while (s1<=mid){
            tmp[k++]=array[s1++];
        }
        while (s2<=end){
            tmp[k++]=array[s2++];
        }
        for (int i = 0; i < tmp.length; i++) {
            array[i+start]=tmp[i];
        }
    }


    //非递归
    public static void mergeSort2(int[] array){
        int gap=1;
        while (gap<array.length){
            for (int i = 0; i < array.length; i+=gap*2) {
                int left=i;
                int mid=left+gap-1;
                if(mid>=array.length){
                    mid=array.length-1;
                }
                int right=mid+gap;
                if(right>=array.length){
                    right=array.length-1;
                }
                merge(array,left,right,mid);
            }
            gap*=2;
        }
    }


    public static void main(String[] args) {
        int[] arr1={12,33,1,5,8,55,88,2};
        mergeSort1(arr1);
        System.out.println("递归的归并排序排序：");
        System.out.println(Arrays.toString(arr1));
        int[] arr2={44,4,5,55,7,8,1,12,9};
        mergeSort2(arr2);
        System.out.println("非递归的归并排序排序：");
        System.out.println(Arrays.toString(arr2));
    }
}
